package pl.un4giv3n.mightvsmagic.action;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import pl.un4giv3n.mightvsmagic.admin.action.PremiumBonusHolder;
import pl.un4giv3n.mightvsmagic.entity.ActivityType;
import pl.un4giv3n.mightvsmagic.entity.PremiumCode;
import pl.un4giv3n.mightvsmagic.entity.User;
import pl.un4giv3n.mightvsmagic.entity.UserActivity;
import pl.un4giv3n.mightvsmagic.utils.ActivityLogUtil;

public class VerifyPremiumCodeAction extends PersistenceAction {

	private static final int DEFAULT_TEETH_BOUGHT = 300;
	private static final int PREMIUM_TEETH_BOUGHT = 2* DEFAULT_TEETH_BOUGHT;
	private static final Logger LOG = Logger.getLogger(VerifyPremiumCodeAction.class);
	private static final long serialVersionUID = 1L;

	private String check; // the string to validate
	private String id = "47641"; // numer ID zarejestrowanego klienta
	private String type = "sms"; // typ konta: C1 - 8 znakowy kod bezobsługowy
	private String code = "VFD2"; // identyfikator usług SMS
	private String returnedString = "";

	@Override
	public String execute() {
		EntityManager entityManager = getEntityManager();
		User user = getSessionUser(entityManager);
		if(user == null){
			entityManager.close();
			addActionError("Zaloguj się");
			return LOGIN;
		}
		HttpClient client = new DefaultHttpClient();
		List<NameValuePair> qparams = new ArrayList<NameValuePair>();
		qparams.add(new BasicNameValuePair("id", id));
		qparams.add(new BasicNameValuePair("code", code));
		qparams.add(new BasicNameValuePair("check", check));
		qparams.add(new BasicNameValuePair("type", type));
		qparams.add(new BasicNameValuePair("del", "1"));
		URI uri = null;
		try {
			uri = URIUtils.createURI("http", "dotpay.pl", -1, "/check_code.php", 
			    URLEncodedUtils.format(qparams, "UTF-8"), null);
		} catch (URISyntaxException e) {
			LOG.error(e.getMessage(),e);
		}
		HttpGet httpget = new HttpGet(uri);
		HttpResponse response;
		try {
			response = client.execute(httpget);
			if(response != null){
				returnedString = EntityUtils.toString(response.getEntity());
			}
		} catch (ClientProtocolException e) {
			addActionError(e.getMessage());
			LOG.error(e.getMessage(),e);
		} catch (IOException e) {
			addActionError(e.getMessage());
			LOG.error(e.getMessage(),e);
		}
		String[] split = returnedString.trim().split("\\s");
		if(split == null || split.length != 3 || !split[0].equals("1") || !split[2].equals("VFD2")){
			addActionError("Niepoprawny kod!");
			return INPUT;
		}
		EntityTransaction transaction = entityManager.getTransaction();
		transaction.begin();
		PremiumCode code = new PremiumCode(user.getId(), check, returnedString);
		entityManager.persist(code);
		UserActivity activity = ActivityLogUtil.createActivity(ActivityType.DRAGONTEETH_BOUGHT, user.getId(), "PremiumCodeId="+code.toString());
		entityManager.persist(activity);
		user.setDragonTeeth(user.getDragonTeeth() + (PremiumBonusHolder.isPremiumBonusActive()? PREMIUM_TEETH_BOUGHT : DEFAULT_TEETH_BOUGHT));
		entityManager.merge(user);
		entityManager.flush();
		transaction.commit();
		entityManager.close();
		return SUCCESS;
	}

	public String getCheck() {
		return check;
	}

	public void setCheck(String check) {
		this.check = check;
	}

}
